import React from 'react';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select, Modal, message } from 'antd';
const { TextArea } = Input;
const confirm = Modal.confirm;
const FormItem = Form.Item;
import { connect } from 'dva';
import { ModalC, ProductGroupTreeC, InputNumberC, SecondHeaderC } from '../../../../comps';
import ico from '../../../../assets/busi/inventoryMnt/positionManage/right_arrow_select.png';
@Form.create()
class transferC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      zqCode2: [],
      miniUnitId: '',
      exchangeCode: '',
      tradingcode: '',
      securityType: '',
      costPrice: '',
      profits: '',
      availableAmount: '',
      disabled: true,
      userName: '',
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'positionManageM/getUser',
      payload: localStorage.getItem('antd-pro-superManId'),
      callback: (data) => {
        if (data) {
          this.setState({
            userName: data.data.name,
          });
        }
      },
    });
  }
  tradingCodeChange = (e) => {
    this.props.dispatch({
      type: 'positionManageM/getTransfer',
      payload: {
        dataDt: moment().format('YYYYMMDD'),
        fundId: e.key,
      },
      callback: (data) => {
        if (data && data.length) {
          this.setState({
            zqCode2: data,
            disabled: false,
          });
        }
      },
    });
  };
  hczqSelecthandle = (value) => {
    const { form } = this.props;
    //先把组合清空
    // form.resetFields(['hccb']);
    const values = value.split(',');
    this.setState({
      miniUnitId: values[0] == null || values[0] == undefined || values[0] == 'null' ? '' : values[0],
      exchangeCode: values[1] == null || values[1] == undefined || values[1] == 'null' ? '' : values[1],
      tradingcode: values[2] == null || values[2] == undefined || values[2] == 'null' ? '' : values[2],
      securityType: values[3] == null || values[3] == undefined || values[3] == 'null' ? '' : values[3],
      costPrice: values[5] == null || values[5] == undefined || values[5] == 'null' ? '' : values[5],
      profits: values[6] == null || values[6] == undefined || values[6] == 'null' ? '' : values[6],
      availableAmount: values[4] == null || values[4] == undefined || values[4] == 'null' ? '' : values[4],
    });
  };
  // 模态框内容
  addForm = () => {
    const { getFieldDecorator } = this.props.form;
    const { zqCode2, costPrice, profits, availableAmount, disabled } = this.state;
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    const formItemLayouts = {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 21,
      },
    };
    const childrenzq = zqCode2.map((item) => {
      return (
        <Select.Option
          key={
            item.id.miniUnitId +
            ',' +
            item.id.exchangeCode +
            ',' +
            item.id.tradingcode +
            ',' +
            item.id.securityType +
            ',' +
            item.availableAmount +
            ',' +
            item.costPrice +
            ',' +
            item.profits
          }
        >{`${item.id.tradingcode}-${item.secuabbr}`}</Select.Option>
      );
    });
    return (
      <div>
        <Form>
          {/* ***************************第一行************************************* */}
          <Row>
            <Col span={11}>
              <SecondHeaderC title='划出' />
              <div style={{ border: '1px solid rgba(153,153,153,0.4)', padding: '20px', borderRadius: '2px' }}>
                <ProductGroupTreeC
                  form={this.props.form}
                  dataIndex='fundId'
                  title='产品组合'
                  authority={'write'}
                  formItemLayout={formItemLayout}
                  multiple={false}
                  rules={[{ required: true, message: `请输入产品组合` }]}
                  onChange={(e) => this.tradingCodeChange(e)}
                />
                <FormItem label='划出证券' {...formItemLayout}>
                  {getFieldDecorator('hcZqCode', {
                    rules: [
                      {
                        required: true,
                        message: '请选择划出证券',
                      },
                    ],
                  })(
                    <Select allowClear showSearch disabled={disabled} placeholder='请选择' optionFilterProp='children' onSelect={this.hczqSelecthandle}>
                      {childrenzq}
                    </Select>,
                  )}
                </FormItem>
                <InputNumberC
                  title='成本'
                  dataIndex='costPrice'
                  placeholder='请输入'
                  min={0}
                  precision={4}
                  // max={999999999999}
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  initialValue={costPrice}
                  // onRef= {ref => { this.state.costPrice = ref }}
                />
                <InputNumberC
                  title='收益'
                  dataIndex='profits'
                  placeholder='请输入'
                  // min={1}
                  // max={999999999999}
                  precision={2}
                  disabled={true}
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  initialValue={profits}
                />
                <InputNumberC
                  title='可用数量'
                  dataIndex='availableAmount'
                  placeholder='请输入'
                  // min={1}
                  // max={999999999999}
                  disabled={true}
                  precision={0}
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  initialValue={availableAmount}
                />
              </div>
            </Col>
            <Col span={2}>
              <div style={{ textAlign: 'center', marginTop: '131px' }}>
                <img src={ico} />
              </div>
            </Col>
            <Col span={11}>
              <SecondHeaderC title='划入' />
              <div style={{ border: '1px solid rgba(153,153,153,0.4)', padding: '20px', height: '265.33px', borderRadius: '2px' }}>
                <ProductGroupTreeC
                  form={this.props.form}
                  dataIndex='fundIds'
                  title='产品组合'
                  formItemLayout={formItemLayout}
                  multiple={false}
                  rules={[{ required: true, message: `请输入产品组合` }]}
                />
                <InputNumberC
                  title='划转数量'
                  dataIndex='amount'
                  placeholder='请输入'
                  precision={0}
                  min={1}
                  max={999999999999}
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  rules={[
                    { required: true, message: `请输入数量` },
                    { pattern: /^[1-9]/, message: '数量不能小于1' },
                  ]}
                />
              </div>
            </Col>
          </Row>
          {/* ***************************第二行************************************* */}
          <Row>
            <Col span={24} style={{ marginTop: '20px' }}>
              <FormItem label='备注' {...formItemLayouts}>
                {getFieldDecorator('descriptionModal')(<TextArea />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  // 确认
  addanOK = () => {
    const {
      form: { validateFields, resetFields },
      type,
      tableData,
    } = this.props;
    validateFields(['fundId', 'zqcode', 'profits', 'costPrice', 'amount', 'fundIds', 'availableAmount', 'descriptionModal'], (err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.amount > fieldsValue.availableAmount) {
        message.warning('调整数量不能大于可用数量');
        return;
      }

      const value = {
        amount: fieldsValue.amount.toString(),
        dataDt: moment().format('YYYYMMDD'),
        exchangeCode: this.state.exchangeCode,
        miniUnitId: this.state.miniUnitId,
        operateBy: this.state.userName,
        operateType: 6,
        price: fieldsValue.costPrice,
        securityType: this.state.securityType,
        tradingcode: this.state.tradingcode,
        remark: fieldsValue.descriptionModal,
      };
      const values2 = {
        amount: fieldsValue.amount.toString(),
        dataDt: moment().format('YYYYMMDD'),
        exchangeCode: this.state.exchangeCode,
        miniUnitId: fieldsValue.fundIds,
        operateType: 7,
        operateBy: this.state.userName,
        tradingcode: this.state.tradingcode,
        remark: fieldsValue.descriptionModal,
        securityType: this.state.securityType,
        price: fieldsValue.costPrice,
      };
      this.props.dispatch({
        type: 'positionManageM/outSecurity',
        payload: value,
        callback: (res) => {
          if (res) {
            this.props.dispatch({
              type: 'positionManageM/inSecurity',
              payload: values2,
              callback: (res) => {
                if (res) {
                  resetFields();
                  this.props.changeVisible();
                  this.props.onRefesh(); //刷新列表
                }
              },
            });
          }
        },
      });
    });
  };

  // 取消
  addanCancel = () => {
    const {
      form: { resetFields },
    } = this.props;
    this.props.changeVisible();
    resetFields();
  };

  render() {
    return (
      <ModalC
        title={'划转证券'}
        visible={this.props.visible}
        maskClosable={false}
        onOk={this.addanOK}
        onCancel={this.addanCancel}
        confirmLoading={this.props.loading.effects['positionManageM/outSecurity'] === true || this.props.loading.effects['positionManageM/inSecurity'] === true}
        width={810}
      >
        <div>{this.addForm()}</div>
      </ModalC>
    );
  }
}
export default connect(({ positionManage, loading }) => ({ positionManage, loading }))(transferC);
